from rest_framework.views import exception_handler
from django.db import DataError
from rest_framework.response import Response
from rest_framework import status
from redis import RedisError

import logging

logger = logging.getLogger('django')  # 生成日志记录对象


def custom_exception_handler(exc, context):
    "自定义异常"
    "原生drf异常处理方法"
    response = exception_handler(exc, context)
    if response is None:  # 如果原生的drf异常处理方法无法识别异常
        view = context['view']
        # 判断是否发生了数据库的异常
        if isinstance(exc, DataError):
            # 数据库异常
            # logger 记录异常
            logger.error('mysql数据库异常！[%s] %s' % (view,exc))
            response = Response({'message':'服务器内部错误'},status=status.HTTP_507_INSUFFICIENT_STORAGE)

        elif isinstance(exc, RedisError):
            logger.error('redis数据库异常！[%s] %s' % (view, exc))
            response = Response({'message': '服务器内部错误'}, status=status.HTTP_507_INSUFFICIENT_STORAGE)
        elif isinstance(exc, ZeroDivisionError):
            response = Response({'message': '0不能作为除数'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    return response
